package ch02.demo;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo6 {
    public static void main(String[] args) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XMl文档，得到一个Document对象
            Document doc = db.parse("src/ch02/demo/demo.xml");
            NodeList list = doc.getElementsByTagName("Brand");
            for (int i = 0; i < list.getLength(); i++) {
                Element brandEl = (Element) list.item(i);
                String brandName = brandEl.getAttribute("name");
                if (brandName.equals("SAMSUNG")) {
                    brandEl.getParentNode().removeChild(brandEl);
                }
            }
            //保存XML文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            StreamResult result = new StreamResult(new FileOutputStream("src/ch02/demo/demo.xml"));
            transformer.transform(domSource, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
